'use strict';

const Controller = require('../core/baseController.js');

class WechatUserController extends Controller {
  async login() {
    const { ctx } = this;
    const { js_code } = ctx.request.body;
    const userInfo = await ctx.service.user.getUserInfoFromWechat(js_code);
    await ctx.service.user.saveUserInfo(userInfo);
    this.success({
      ...userInfo,
      token: userInfo.openid,
    });
  }
  async getUserInfo() {
    console.log(this.token);
    const userInfo = await this.app.mysql.get('wechatuser', { openid: this.token });
    this.success(userInfo);
  }
  async updateUserInfo() {
    const { ctx } = this;
    const { avatarUrl, nickName, gender, country, province, city } =
      ctx.request.body;
    const result = await this.app.mysql.update(
      'wechatuser',
      { avatarUrl, nickName, gender, country, province, city },
      {
        where: {
          openid: this.token,
        },
      }
    );
    const updateSuccess = result.affectedRows === 1;
    if (updateSuccess) {
      this.success('更新成功');
    } else {
      this.notFound('更新失败');
    }
  }
}

module.exports = WechatUserController;
